﻿
Public MustInherit Class bytesbase(Of T)
    Implements toBytes, fromBytes, ICloneable

    Protected d As T

    Public MustOverride Sub frombytes(ByVal b As bytes) Implements frombytes.frombytes
    Public MustOverride Function tobytes() As bytes Implements tobytes.tobytes

    Public Sub New()
        d = Nothing
    End Sub

    Public Sub New(ByVal i As T)
        copy(d, i)
    End Sub

    Public Shared Widening Operator CType(ByVal this As bytesbase(Of T)) As T
        If Not this Is Nothing Then
            Dim rtn As T = Nothing
            copy(rtn, this.d)
            Return rtn
        Else
            Return Nothing
        End If
    End Operator

    Public NotOverridable Overrides Function ToString() As String
        Return Convert.ToString(d)
    End Function

    Public Function Clone() As Object Implements System.ICloneable.Clone
        Dim rtn As bytesbase(Of T) = Nothing
        rtn = alloc(Me)
        copy(rtn.d, d)
        Return rtn
    End Function
End Class

Public Class bytesbytes
    Inherits bytesbase(Of bytes)

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal i As bytes)
        MyBase.New(i)
    End Sub

    Public Overrides Sub frombytes(ByVal b As bytes)
        copy(d, b)
    End Sub

    Public Overrides Function tobytes() As bytes
        Dim rtn As bytes = Nothing
        copy(rtn, d)
        Return rtn
    End Function

    Public Overloads Shared Widening Operator CType(ByVal this As bytes) As bytesbytes
        Return New bytesbytes(this)
    End Operator
End Class

Public Class bytesBoolean
    Inherits bytesbase(Of Boolean)

    Public Const TRUE_VALUE As Byte = maxUInt8

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal i As Boolean)
        MyBase.New(i)
    End Sub

    Public Overrides Sub frombytes(ByVal b As bytes)
        d = (b.size() = 1 AndAlso b(0) = TRUE_VALUE)
    End Sub

    Public Overrides Function tobytes() As bytes
        Return New bytes(TRUE_VALUE)
    End Function

    Public Overloads Shared Widening Operator CType(ByVal this As Boolean) As bytesBoolean
        Return New bytesBoolean(this)
    End Operator
End Class